import React from 'react';
import { connect, routerRedux } from 'dva';
import DocumentTitle from 'react-document-title';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Input, message } from 'antd';
import styles from './login.less';
import maatLogin from '../../assets/frame/login/login_logo.png';
import maatLoginT from '../../assets/frame/login/login_logoText.png';
import bgLogin from '../../assets/frame/login/login_bg.png';
import { environmentPath, geestcId } from '../../utils/environmentPath';

@Form.create()
@connect(({ login }) => ({ login }))
class LoginP extends React.PureComponent {
  state = {
    isInner: environmentPath(), // 判断是内网还是外网
    timeCount: 60, // 计时器
    isShowTime: false, // 展示倒计时
  };

  getPageTitle() {
    return '';
    // const { routerData, location } = this.props;
    // const { pathname } = location;
    // let title = '投资组合管理系统';
    // if (routerData[pathname] && routerData[pathname].name) {
    //     title = `${routerData[pathname].name} - 投资组合管理系统`;
    // }
    // return title;
  }

  UNSAFE_componentWillMount() {}

  componentDidMount() {
    // 监听enter键触发登录
    document.addEventListener('keydown', this.onkeydown);
    // 外网 注册极验
    if (!this.state.isInner)
      this.props.dispatch({
        type: 'login/registerGeetest', // 注册校验接口
        payload: {
          // cId:geestcId(),
        },
        callback: (data) => {
          if (data && data.challenge) {
            // 注册成功
            // 请检测data的数据结构， 保证cid, data.challenge有值
            // eslint-disable-next-line consistent-this
            const that = this;
            if (data.offline == true) {
              // data.offline==true 极验系统宕机需要调用login/failbackValidate
              console.log('极验系统宕机了');
              document.getElementById('verificationCode').onclick = function () {
                that.props.dispatch({
                  type: 'login/failbackValidate', // 校验接口
                  payload: {
                    challenge: data.challenge,
                    // "cId":data.cid,
                  },
                  callback: (result) => {
                    if (result.code === 0 && result.value.result === 'success') {
                      // 二次验证成功 发送验证码
                      that.verificationCode();
                    } else {
                      // 处理二次验证失败业务逻辑
                      message.error('校验失败！');
                    }
                  },
                });
              };
              return;
            }
            data.cid = geestcId(); // 获取cid，一定需要传 要不图形code不出来
            initGeetest(
              {
                ...data,
                lang: 'zh-cn', // 语言
                product: 'bind',
              },
              function (gt) {
                gt.onReady(function () {
                  console.log('bind ready');
                  document.getElementById('verificationCode').onclick = function () {
                    gt.verify();
                  };
                }).onSuccess(function () {
                  const result = gt.getValidate();
                  // console.log(result)
                  if (!result) {
                    console.log('gt验证失败');
                    return;
                  }
                  that.props.dispatch({
                    type: 'login/validateGeetest', // 校验接口
                    payload: {
                      challenge: result.geetest_challenge,
                      // "cId":data.cid,
                    },
                    callback: (result) => {
                      if (result.code === 0 && result.value.result === 'success') {
                        // 二次验证成功 发送验证码
                        that.verificationCode();
                      } else {
                        // 处理二次验证失败业务逻辑
                        message.error('校验失败！');
                      }
                    },
                  });
                });
              },
            );
          }
        },
      });
  }

  componentWillUnmount() {
    // 监听enter键触发登录
    document.removeEventListener('keydown', this.onkeydown);
    //
    if (this.countdown) {
      clearInterval(this.countdown);
      this.countdown = null;
    }
  }

  // enter响应
  onkeydown = (e) => {
    if (e.keyCode === 13) {
      this.onload();
    }
  };

  // 登录按钮响应
  onload = () => {
    const {
      dispatch,
      form: { validateFields },
    } = this.props;
    const arr = this.state.isInner ? ['UserLayout_longNo', 'UserLayout_longPassword'] : ['UserLayout_longNo', 'UserLayout_longPassword', 'verificationCodeInput'];
    validateFields(arr, (err, vals) => {
      if (err) return;
      const values = {
        userId: vals.UserLayout_longNo,
        userPassword: vals.UserLayout_longPassword,
      };
      // 调登录接口
      if (this.state.isInner) {
        // 内网 通过maat后端登录
        dispatch({
          type: 'login/urlLogin',
          payload: values,
          callback: (res) => {
            if (res) {
              // 跳转框架层
              dispatch(
                routerRedux.push({
                  pathname: '/',
                }),
              );
            }
          },
        });
      } else {
        // 外网  通过heimdall 登录
        dispatch({
          type: 'login/heimdallLogin',
          payload: {
            username: values.userId, // 用户名
            password: values.userPassword, // 密码
            sms_username: values.userId, // 用户名
            sms_password: vals.verificationCodeInput,
          },
          callback: () => {
            // 跳转框架层
            dispatch(
              routerRedux.push({
                pathname: '/',
              }),
            );
          },
        });
      }
    });
  };

  // 倒计时
  countDownFn = () => {
    const { timeCount } = this.state;
    let count = timeCount;
    if (count === 0) {
      clearInterval(this.countdown); // 清除循环
      this.countdown = null;
      this.setState({
        isShowTime: false,
        timeCount: 60,
      });
      return;
    }
    count--;
    this.setState({
      timeCount: count,
    });
  };

  // 获取验证码
  verificationCode = () => {
    const {
      dispatch,
      form: { validateFields },
    } = this.props;
    if (this.state.isShowTime) return;
    validateFields(['UserLayout_longNo'], (err, vals) => {
      if (err) {
        message.error('请输入正确的手机号');
        return;
      }
      this.setState({
        isShowTime: true,
      });
      this.countDownFn();
      this.countdown = setInterval(() => {
        this.countDownFn();
      }, 1000);
      // 获取验证码
      this.props.dispatch({
        type: 'login/getVerificationCode',
        payload: {
          username: vals.UserLayout_longNo, // 用户名
        },
        callback: () => {
          console.log('发送失败，清除计时器');
          clearInterval(this.countdown); // 清除循环
          this.countdown = null;
          this.setState({
            isShowTime: false,
            timeCount: 60,
          });
        },
      });
    });
  };

  render() {
    const { isInner, isShowTime, timeCount } = this.state;
    const { getFieldDecorator } = this.props.form;
    const rules =
      isInner == false
        ? [
            {
              required: true,
              message: '请输入手机号',
            },
            {
              validateTrigger: 'onBlur',
              pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
              message: '请输入正确的手机号！',
            },
          ]
        : [
            {
              required: true,
              message: '请输入账号',
            },
          ];
    return (
      <DocumentTitle title={this.getPageTitle()}>
        <div className={styles.container}>
          <div className={styles.login}>
            <div className={styles.leftLogin}>
              <div className={styles.maatLogin}>
                <span>
                  <img src={maatLogin}></img>
                </span>
                <span className={styles.maatLoginT}>
                  <img src={maatLoginT}></img>
                </span>
              </div>
              <div className={styles.maatTitle}>
                <div className={styles.maatTitleC}>投资组合管理系统</div>
                <div className={styles.maatTitleE}>PORTFOLIO MANAGEMENT SYSTEM</div>
              </div>
              <div className={styles.bgLogin}>
                <img src={bgLogin}></img>
              </div>
            </div>
            <div className={styles.rightLogin}>
              <div className={styles.loginBox}>
                <div className={styles.loginTitle}>欢迎登录</div>
                <Form.Item>
                  {getFieldDecorator('UserLayout_longNo', {
                    rules,
                  })(<Input className={styles.loginInputName} placeholder={isInner ? '请输入账号' : '请输入手机号'} />)}
                </Form.Item>
                <Form.Item>
                  {getFieldDecorator('UserLayout_longPassword', {
                    rules: [
                      {
                        required: true,
                        message: '请输入密码',
                      },
                    ],
                  })(<Input type='password' className={styles.loginInputPassword} placeholder='请输入密码' />)}
                </Form.Item>
                <div className={styles.verificationCode}>
                  <Form.Item>
                    {getFieldDecorator('verificationCodeInput', {
                      rules: [
                        {
                          required: true,
                          message: '请输入验证码',
                        },
                      ],
                    })(
                      <Input
                        className='verificationCodeInput'
                        placeholder='请输入验证码'
                        suffix={
                          <a id='verificationCode' disabled={isInner ? true : !!isShowTime}>
                            {isShowTime ? `重新发送(${timeCount}s)` : '获取验证码'}
                          </a>
                        }
                        disabled={isInner}
                      />,
                    )}
                  </Form.Item>
                </div>
                <Button onClick={() => this.onload()} className={styles.loginButton}>
                  登录
                </Button>
              </div>
            </div>
          </div>
        </div>
      </DocumentTitle>
    );
  }
}

export default LoginP;
